package com.itfreer.data.db;

import java.util.List;
import java.util.Map;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.itfreer.data.db.dao.DBRegistDao;
import com.itfreer.data.db.dao.DataDao;
import com.itfreer.data.db.entity.DBRegistEntity;
import com.itfreer.form.api.PageInfo;

@Component
public class JdbcDataDaoImp implements DataDao {

	@Autowired
	protected DBRegistDao dbrRegistDao;

	@SuppressWarnings({ "unchecked", "deprecation" })
	@Override
	public List<Map<String, Object>> getRows(String id, PageInfo pInfo) {
		// 获取数据库注册实体对象
		DBRegistEntity dbentity = dbrRegistDao.getEntity(id);
		if (dbentity == null) {
			return null;
		}
		try {
			// 获取session对象
			Session session = HibernateDataUtils.getOpenSession(dbentity);
			Transaction tx = session.beginTransaction();
			String sql = HibernateDataUtils.toSelectSql(dbentity, pInfo.getQueryFields(), null, null);
			// 默认从0 开始，即第一条记录
			int startIndex = 0;

			if (pInfo.getPageSize() <= 0) {
				// 默认每次查询1000条
				pInfo.setPageSize(1000);
			}

			if (pInfo.getPageIndex() >= 1) {
				startIndex = pInfo.getPageSize() * (pInfo.getPageIndex() - 1);
			}

			List<Map<String, Object>> list = HibernateDataUtils
					.toUpper(session.createNativeQuery(sql)
							.setFirstResult(startIndex)
							.setMaxResults(pInfo.getPageSize())
							.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list());
			tx.commit();
			session.close();
			return list;
		} catch (HibernateException e) {
			e.printStackTrace();
			return null;
		}

	}

	@SuppressWarnings("unchecked")
	@Override
	public Long getRowCounts(String id, Map<String, Object> where) {
		DBRegistEntity dbentity = dbrRegistDao.getEntity(id);
		if (dbentity == null) {
			return null;
		}

		try {
			// 获取session对象
			Session session = HibernateDataUtils.getOpenSession(dbentity);
			Transaction tx = session.beginTransaction();
			String sql = HibernateDataUtils.toCountSql(dbentity, null);
			List<Object> list = session.createNativeQuery(sql).list();
			Long count = Long.parseLong(list.get(0).toString());
			tx.commit();
			session.close();
			return count;
		} catch (HibernateException e) {
			e.printStackTrace();
			return null;
		}
	}

}
